package com.nari.kmd_dataservice.service.impl;

import com.nari.core.tool.utils.RedisUtil;
import com.nari.kmd_dataservice.constant.ConstantParameter;
import com.nari.kmd_dataservice.constant.GlobalVariable;
import com.nari.kmd_dataservice.mapper.ServerMapper;
import com.nari.kmd_dataservice.pojo.dto.targetResponse.TargerResponseDto;
import com.nari.kmd_dataservice.pojo.dto.targetVerify.TargerVerifyDto;
import com.nari.kmd_dataservice.pojo.entity.LaUser;
import com.nari.kmd_dataservice.pojo.entity.User;
import com.nari.kmd_dataservice.pojo.request.targetResponse.TargerResponseRequest;
import com.nari.kmd_dataservice.service.LoadPlatformService;
import com.nari.kmd_dataservice.util.GsonUtils;
import com.nari.kmd_dataservice.util.NetworkUtil;
import com.nari.kmd_dataservice.util.SM3;
import com.nari.kmd_dataservice.util.SM4;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName: LoadPlatformServiceImpl
 * @Description: 请求负荷聚合平台服务
 * @Author: zhangnaijiang
 * @Date: 2022/01/27 19:17
 * @Version 1.0.0
 */
@Service
@Slf4j
public class LoadPlatformServiceImpl implements LoadPlatformService {
    @Autowired
    private RestTemplate restTemplate;
    @Resource
    ServerMapper serverMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public TargerVerifyDto targetVerify(LaUser laUser) throws Exception {
        log.info("电力需求响应系统认证验证获取token，{}",laUser);
        String body = getBodyFromLoadPlatform("targetVerify", laUser, GsonUtils.toJsonWtihNullField(laUser), null);
        TargerVerifyDto targerVerifyDto = GsonUtils.fromJson(body, TargerVerifyDto.class);
        if("01".equals(targerVerifyDto.getStatus())){
            if(targerVerifyDto.getToken()!=null && targerVerifyDto.getRegistRationId()!=null){
                laUser.setRegistRationId(targerVerifyDto.getRegistRationId());
                laUser.setLastLoginTime(new Date());
                serverMapper.updateLaUser(laUser);
                //token存redis，缓存10分钟
                redisUtil.set(targerVerifyDto.getRegistRationId(), targerVerifyDto.getToken(), ConstantParameter.laTokenOutMinute*60);
            }
        }
        return targerVerifyDto;
    }

    @Override
    public boolean publishResponseEvent(TargerResponseRequest targerResponseRequest) {
        boolean result = false;
        LaUser laUser = serverMapper.selectLaUserByID(targerResponseRequest.getRegistRationId());
        try {
            String body = getBodyFromLoadPlatform("targetResponse", laUser, GsonUtils.toJsonWtihNullField(targerResponseRequest), null);
            TargerResponseDto targerResponseDto = GsonUtils.fromJson(body, TargerResponseDto.class);
            if("01".equals(targerResponseDto.getStatus()) && targerResponseRequest.getEventId().equals(targerResponseDto.getEventId())){
                result = true;
            }
        }catch (Exception e){
            log.error("发布需求响应事件异常", e);
        }
        if(result){
            serverMapper.updateSuccessResponseEventRangeList(targerResponseRequest, laUser.getLaRegistRationId());
            int notPublishResponseEventRangeCount = serverMapper.getNotPublishResponseEventRangeCount(targerResponseRequest.getEventId());
            log.info("事件{}未发布范围数量{}", targerResponseRequest.getEventId(), notPublishResponseEventRangeCount);
            if(notPublishResponseEventRangeCount==0){
                serverMapper.updateSuccessResponseEvent(targerResponseRequest.getEventId());
            }
        }
        else{
            serverMapper.updateFailResponseEventRangeList(targerResponseRequest, laUser.getLaRegistRationId());
        }
        return result;
    }

    @Override
    public String getBodyFromLoadPlatform(String requestURI, LaUser laUser, String jsonParameter, String token) throws Exception {
//        String token = null;
        if(!"targetVerify".equals(requestURI) && token==null){
            token = getLaTokenByRegistRationId(laUser.getRegistRationId());
        }
//        String url = "http://"+ "40.72.118.23"+"/openmanage/v1/hebei/server/electric/"+requestURI;
//        String url = "https://127.0.0.14:443/server/"+requestURI;
        User user = serverMapper.selectUserByID(laUser.getLaRegistRationId());
        log.info("user={}",user);
        log.info("laUser={}",laUser);
        String url = NetworkUtil.getUrl(user)+"/"+requestURI;
        if(laUser.getSysType()==2){
            url = laUser.getRealUrl()+"?method=com.bangdao.xavpp.open.prov."+requestURI;
        }
        else{
            url = laUser.getRealUrl()+"/"+requestURI;
        }
        log.info("url={}",url);

        String encryptBody;
        String sign;
        if(GlobalVariable.checkSM4){
            log.info("请求负荷聚合平台URI：{}，加密前参数：{}", requestURI, jsonParameter);
            if(laUser.getSysType()==0){
                encryptBody = SM4.encryptEcb(ConstantParameter.localSM4Key, jsonParameter);
            }
            else{
                encryptBody = SM4.encryptEcb(laUser.getLaSm4Key(), jsonParameter);
            }
            sign = SM3.encrypt(encryptBody);
            if(laUser.getSysType()==1){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("encryptStr", encryptBody);
                encryptBody = jsonObject.toString();
            }
            log.info("请求负荷聚合平台URI：{}，加密参数：{}", requestURI, encryptBody);
        }
        else{
            encryptBody = jsonParameter;
            sign = SM3.encrypt(encryptBody);
            log.info("请求负荷聚合平台URI：{}，明文参数：{}", requestURI, encryptBody);
        }
        log.info("请求负荷聚合平台URI：{}，签名：{}", requestURI, sign);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Type", "application/json");
        httpHeaders.set("sign", sign);
        if(token!=null){
            httpHeaders.set("token", token);
        }

        HttpEntity<String> entity = new HttpEntity<>(encryptBody, httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        String body = exchange.getBody();
        HttpHeaders httpHeadersResponse = exchange.getHeaders();
        sign = httpHeadersResponse.getFirst("sign");
        log.info("请求负荷聚合平台URI：{}，sign:{}，响应：{}", requestURI, sign, body);

        //{"status":200,"message":"","data":}

        String decryptBody;
        String sm3sign;
        if(GlobalVariable.checkSM4){
            if(laUser.getSysType()==1){
                JSONObject jsonObject = new JSONObject(body);
                JSONObject jsonObject_data;
                int status = jsonObject.getInt("status");
                if(status==200){
                    jsonObject_data = (JSONObject) jsonObject.get("data");
                }
                else if(status<10){
                    jsonObject_data = jsonObject;
                }
                else{
                    throw new Exception(jsonObject.getString("message"));
                }

                String dtoEncryptStr = jsonObject_data.getString("dtoEncryptStr");
                sm3sign = SM3.encrypt(dtoEncryptStr);
                decryptBody = SM4.decryptEcb(laUser.getLaSm4Key(), dtoEncryptStr);
                log.info("请求负荷聚合平台URI：{}，响应解密：{}", requestURI, decryptBody);
            }
            else{
                String dtoEncryptStr = body;
                sm3sign = SM3.encrypt(dtoEncryptStr);
                if(laUser.getSysType()==0){
                    decryptBody = SM4.decryptEcb(ConstantParameter.localSM4Key, dtoEncryptStr);
                }
                else{
                    decryptBody = SM4.decryptEcb(laUser.getLaSm4Key(), dtoEncryptStr);
                }
            }
        }
        else{
            if(laUser.getSysType()==1){
                JSONObject jsonObject = new JSONObject(body);
                JSONObject jsonObject_data;
                int status = jsonObject.getInt("status");
                if(status==200){
                    jsonObject_data = (JSONObject) jsonObject.get("data");
                }
                else if(status<10){
                    jsonObject_data = jsonObject;
                }
                else{
                    throw new Exception(jsonObject.getString("message"));
                }
                decryptBody = jsonObject_data.toString();
                sm3sign = SM3.encrypt(decryptBody);
            }
            else{
                decryptBody = body;
                sm3sign = SM3.encrypt(decryptBody);
            }
        }
        if(GlobalVariable.checkSM3){
            if(sign==null || !sm3sign.equalsIgnoreCase(sign)){
                throw new Exception("请求负荷聚合平台URI："+requestURI+"，sm3校验失败，"+sign+"<->"+sm3sign);
            }
        }
        return decryptBody;
    }

    @Override
    public String getLaTokenByRegistRationId(String registRationId) throws Exception {
        String token = null;
        Object redisValue = redisUtil.get(registRationId);
        if(redisValue!=null){
            token = (String)redisValue;
        }
        else{
            LaUser laUser = serverMapper.selectLaUserByID(registRationId);
            TargerVerifyDto targerVerifyDto = targetVerify(laUser);
            if(targerVerifyDto!=null){
                token = targerVerifyDto.getToken();
            }
        }
        log.info("获取token，registRationId:{}，token:{}", registRationId, token);
        return token;
    }
}
